import 'package:flutter/material.dart';

import 'random_joke_scope.dart';

class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Random Joke Generator')),
      body: const SizedBox.expand(
        child: Stack(
          alignment: Alignment.center,
          children: [
            _RefreshingBanner(),
            _JokeBody(),
            Positioned(bottom: 20, child: _RefreshButton()),
          ],
        ),
      ),
    );
  }
}

class _RefreshingBanner extends StatelessWidget {
  const _RefreshingBanner();

  @override
  Widget build(BuildContext context) {
    final state = RandomJokeScope.of(context).state;
    if (!state.isRefreshing) {
      return const SizedBox.shrink();
    }

    return const Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: LinearProgressIndicator(),
    );
  }
}

class _JokeBody extends StatelessWidget {
  const _JokeBody();

  @override
  Widget build(BuildContext context) {
    final state = RandomJokeScope.of(context).state;

    if (state.isLoading && !state.hasJoke) {
      return const CircularProgressIndicator();
    }

    if (state.hasError) {
      return const Text('Error fetching joke');
    }

    if (state.hasJoke) {
      final joke = state.joke!;
      return SelectableText(
        '${joke.setup}\n\n${joke.punchline}',
        textAlign: TextAlign.center,
        style: const TextStyle(fontSize: 24),
      );
    }

    return const SizedBox.shrink();
  }
}

class _RefreshButton extends StatelessWidget {
  const _RefreshButton();

  @override
  Widget build(BuildContext context) {
    final refresh = RandomJokeScope.of(context).refresh;

    return ElevatedButton(
      onPressed: () => refresh(),
      child: const Text('Get another joke'),
    );
  }
}
